package com.itheima.dubbo.api;

import com.tanhua.domain.mogo.Comment;
import com.tanhua.domain.mogo.Publish;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.CommentApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;


@Service
@Slf4j
public class CommentApiImpl implements CommentApi {
    @Autowired
    private MongoTemplate mongoTemplate;


    //分页查询某一动态的评论列表
    @Override
    public PageResult<Comment> findComments(int page, int pagesize, String publishId) {
        //查询条件publishId动态id， commentType评论类型2（2是评论，1是点赞，3是喜欢）
        Criteria criteria=Criteria.where("publishId").is(new ObjectId(publishId))
                           .and("commentType").is(2);
        //设置分页和排序
        Query query = new Query(criteria)
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page-1,pagesize));

        //查询
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);
        long count = mongoTemplate.count(query, Comment.class);
        int pages=(int) Math.ceil(count*1.0/pagesize);
        return  new PageResult<Comment>((int)count,page,pages,pagesize,commentList);

    }


    //分页查询针对某一用户的评论列表

    @Override
    public PageResult<Comment> findCommentsByUser(Long userId, int commentType, int page, int pagesize) {
        Query query = new Query(Criteria.where("publishUserId").is(userId)
                .and("commentType").is(commentType))
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page-1,pagesize));
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);
        long count=mongoTemplate.count(query,Comment.class);
        int pages= (int) Math.ceil(count*1.0/pagesize);


        return  new PageResult<>((int)count,page,pagesize,pages,commentList);


    }

    @Override
    public PageResult<Comment> findCommentList(int page, int pagesize, String publishId) {
       Criteria criteria= Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(2);
        Query query = new Query(criteria)


                .with(Sort.by(Sort.Order.desc("likeCount"),Sort.Order.desc("created")))
                .with(PageRequest.of(page-1,pagesize));
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);
        long count=mongoTemplate.count(query,Comment.class);
        int pages=(int)Math.ceil(count*1.0/pagesize);

        return new PageResult<>((int)count,pages,page,pagesize,commentList);
    }

    @Override
    public long save(Comment comment) {
        //1.补全数据
        comment.setId(ObjectId.get());
        comment.setCreated(System.currentTimeMillis());
        //2.保存评论
        mongoTemplate.save(comment);
        //3.更新动态的评论数量加1 得到更新后的动态publish
        // 如果操作类型commentType是1：是点赞，要对publish的likeCount+1
        // 如果操作类型commentType是2：是文字评论，要对publish的commentCount+1
        // 如果操作类型commentType是3：是喜欢，要对publish的loveCount+1
        Criteria criteria=Criteria.where("id").is(comment.getPublishId());
        Query query = new Query(criteria);
        Update update = new Update().inc(getColumnName(comment.getCommentType()), 1);
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);

        Publish publish = mongoTemplate.findAndModify(query, update, options, Publish.class);
        //返回最新的计数
        return getCount(publish,comment.getCommentType());
    }

    @Override
    public long remove(Comment comment) {
        //删除评论记录
        Criteria criteria=Criteria.where("publishId").is(comment.getPublishId())
                .and("userId").is(comment.getUserId())
                .and("commentType").is(comment.getCommentType())
                 .and("pubType").is(comment.getPubType());
        Query query = new Query(criteria);
          mongoTemplate.remove(query,Comment.class);

          //2.更新动态的计数：-1
        query=new Query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update().inc(getColumnName(comment.getCommentType()),-1);
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);
        Publish publish = mongoTemplate.findAndModify(query, update, options, Publish.class);
        //获取返回最新的计数
        return  getCount(publish,comment.getCommentType());

    }

    private long getCount(Publish publish, Integer  commentType) {
        if (commentType==1){
            //点赞了 要获取最新的点赞数
            return publish.getLikeCount();
        }else if (commentType==2){
            //文字评论了 要获取最新的文字评论数
            return publish.getCommentCount();

        }else if (commentType==3){
            //喜欢了 要获取最新的喜欢数
            return publish.getLoveCount();
        }
        return 0;


    }

    private String getColumnName(Integer commentType) {
        if (commentType==1){
            //点赞了，要更新的是likeCount
            return "likeCount";

        }else if (commentType==2){
            //文字评论 要更新的是commentCount
            return "commentCount";
        }else if (commentType==3){
            //喜欢了 ，要更新的是loveCount
            return "loveCount";
        }
        return "";

    }


}
